#!/usr/bin/env python3
"""
验证导入语句修改后的代码功能正确性
"""

import os
import sys
import py_compile
from pathlib import Path

# 需要验证的文件列表
files_to_check = [
    "database_backup/config/global_config.py",
    "database_backup/config/backup_config.py",
    "database_backup/backup_mariadb.py",
    "database_backup/backup_postgresql.py",
    "database_backup/cli_main.py"
]

def check_syntax(file_path):
    """检查文件语法是否正确
    
    参数:
        file_path (str): 文件路径
        
    返回:
        bool: 语法是否正确
    """
    try:
        py_compile.compile(file_path, doraise=True)
        print(f"✓ {file_path} 语法检查通过")
        return True
    except py_compile.PyCompileError as e:
        print(f"✗ {file_path} 语法错误: {e}")
        return False
    except Exception as e:
        print(f"✗ {file_path} 检查失败: {e}")
        return False

def check_imports(file_path):
    """检查文件中的导入语句是否都在顶部
    
    参数:
        file_path (str): 文件路径
        
    返回:
        bool: 导入语句是否都在顶部
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 找到第一个非导入、非注释、非空行的行号
        first_non_import_line = 0
        in_docstring = False
        docstring_quotes = None
        
        for i, line in enumerate(lines):
            stripped = line.strip()
            
            # 跳过空行
            if not stripped:
                continue
                
            # 处理文档字符串
            if '"""' in stripped or "'''" in stripped:
                if not in_docstring:
                    in_docstring = True
                    docstring_quotes = '"""' if '"""' in stripped else "'''"
                    # 检查是否在同一行结束
                    if stripped.count(docstring_quotes) >= 2:
                        in_docstring = False
                else:
                    if docstring_quotes in stripped:
                        in_docstring = False
                continue
                
            if in_docstring:
                continue
                
            # 跳过注释行
            if stripped.startswith('#'):
                continue
                
            # 检查是否是导入语句
            if stripped.startswith('import ') or stripped.startswith('from '):
                continue
                
            # 找到第一个非导入行
            first_non_import_line = i
            break
        
        # 检查后面是否还有导入语句
        for i in range(first_non_import_line, len(lines)):
            stripped = lines[i].strip()
            
            # 跳过空行和注释
            if not stripped or stripped.startswith('#'):
                continue
                
            # 检查是否是导入语句
            if stripped.startswith('import ') or stripped.startswith('from '):
                print(f"✗ {file_path} 第{i+1}行有非顶部导入: {stripped}")
                return False
        
        print(f"✓ {file_path} 导入语句检查通过")
        return True
        
    except Exception as e:
        print(f"✗ {file_path} 导入检查失败: {e}")
        return False

def main():
    """主函数"""
    print("开始验证修改后的文件...")
    print("=" * 50)
    
    all_passed = True
    
    for file_path in files_to_check:
        if not os.path.exists(file_path):
            print(f"✗ 文件不存在: {file_path}")
            all_passed = False
            continue
            
        # 检查语法
        if not check_syntax(file_path):
            all_passed = False
            
        # 检查导入语句
        if not check_imports(file_path):
            all_passed = False
    
    print("=" * 50)
    if all_passed:
        print("✓ 所有文件验证通过！")
        return 0
    else:
        print("✗ 部分文件验证失败！")
        return 1

if __name__ == "__main__":
    sys.exit(main())